using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Client.Hotfix
{
    /// <summary>
    /// 类型和特性对的辅助类
    /// </summary>
    /// <typeparam name="T">特性类型</typeparam>
    public class TypeAttributePair<T> where T : Attribute
    {
        public Type Type { get; set; }
        public T Attribute { get; set; }
    }
    public class AssemblyHelper
    {
        static public Assembly GetRunningAssembly(string name)
        {
            return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(assembly => assembly.GetName().Name.Equals(name));
        }


        /// <summary>
        /// 获取指定程序集中所有带有特定特性的类型信息
        /// </summary>
        /// <typeparam name="T">特性类型</typeparam>
        /// <param name="assemblyName">程序集名称</param>
        /// <returns>包含类型和特性信息的列表，如果没有找到则返回空列表</returns>
        public static List<TypeAttributePair<T>> GetAttribute4Assembly<T>(string assemblyName) where T : Attribute
        {
            Assembly assembly = GetRunningAssembly(assemblyName);
            if (assembly == null)
            {
                return null;
            }

            try
            {
                var typesWithAttribute = assembly.GetTypes()
                    .Where(type => type.IsDefined(typeof(T), false) && !type.IsAbstract && !type.IsInterface)
                    .SelectMany(type =>
                    {
                        var attributes = type.GetCustomAttributes(typeof(T), false).Cast<T>();
                        return attributes.Select(attr => new TypeAttributePair<T>
                        {
                            Type = type,
                            Attribute = attr
                        });
                    })
                    .ToList();

                return typesWithAttribute;
            }
            catch
            {
                return null;
            }

        }
    }
}

